package com.lgx.common.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lgx.common.entity.Image;
import com.lgx.common.service.IImageService;
import com.lgx.common.util.ImageConstants;
import com.lgx.common.web.Constants;
import com.lgx.common.web.util.FileUtils;
import com.lgx.right.entity.User;

public class CkeditorImageUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CkeditorImageUploadServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置最多只允许在内存中存储的数据,单位:字节
        factory.setSizeThreshold(4096);  
        //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setSizeMax(FileUtils.UPLOAD_MAX_SIZE); 
        
        User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
        try {  
            List<?> fileItems = upload.parseRequest(request);  
            Iterator<?> iter = fileItems.iterator();  
            while (iter.hasNext()) {  
                FileItem item = (FileItem) iter.next();  
                if (!item.isFormField()) {  
                	try {  
                		
                		String name = item.getName();  
 	                    String[] names = name.split("\\"+System.getProperty("file.separator"));
 	                    name = names[names.length-1];
 	                    names = name.split("\\.");
 	                    name = names[names.length-2];
 	                    
 	                    Image image = new Image();
 	                    name = "image_"+System.currentTimeMillis();
 	                    image.setName(name);
 	                    image.setIsDelete("0");
 	                    image.setCreateDate(new Date());
 	                    image.setCreateName(user.getUsername());
 	                    image.setSize(item.getSize());
 	                    
 	                    String uploadPath = FileUtils.uploadPath();
 	                    String sourcePath = uploadPath + System.getProperty("file.separator") + name+".jpg";
                		
 	              		item.write(new File(sourcePath)); 
                		
                		String[] path = sourcePath.split("\\"+System.getProperty("file.separator"));
	                    sourcePath = path[path.length-3]+"/"+ path[path.length-2]+"/"+ path[path.length-1];
	                    image.setFilePath(sourcePath);
	                    
	                    ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
	                    IImageService imageService = (IImageService) ac.getBean("imageService");
	                    
	                    imageService.createImage(image);
	                    
	                    PrintWriter out = response.getWriter();
	                    //CKEditorFuncNum就是在提交上传文件的同时传递到后台的request内容，表明应该插入到编辑器中的位置
	                    String callback = request.getParameter("CKEditorFuncNum"); 
	                    out.println("<script type=\"text/javascript\">"); 
	                    out.println("window.parent.CKEDITOR.tools.callFunction(" + callback 
	                    		+ ",'" + ImageConstants.IMG_SERVER_URL + "/" + image.getFilePath() + "',''" + ")"); 
	                    out.println("</script>");
	                    out.flush(); 
	                    out.close();
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        } catch (FileUploadException e) {  
            e.printStackTrace();  
            System.out.println(e.getMessage() + "结束");  
        } 
        
	}
}
